<?php
/*----------------------------------------------------------------------
 * 自定义公共函数
 * Author: ming.nie
----------------------------------------------------------------------*/

/**
 * 获取是否数组选项
 * @return array     结果
 * @author ming.nie
 */
function getYesOrNo() {
    $result = array(
        1 => '是',
        2 => '否',
    );
    return $result;
}

/**
 * 影院用户状态
 * @return array 
 * @author ming.nie
 */
function getCinemaStatusOptions() {
    $result = array(
        1 => '使用中',
        2 => '已停用',
    );
    return $result;
}

/**
 * 检测验证码
 * @param  integer $id 验证码ID
 * @return boolean     检测结果
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function check_verify($code, $id = 1){
    $verify = new \Think\Verify();
    return $verify->check($code, $id);
}

/**
 * 全局授权操作数组
 * @return array 
 * @author ming.nie
 */
function getGlobalPermissions() {
    $result = array(
        U('Index/index'),
        U('Agent/insert'),
        U('Agent/update'),
    );
    return $result;
}

/**
 * 公司充值账户
 * @return array     结果
 * @author ming.nie
 */
function getBankAccountOptions() {
    $result = array(
        1 => '中国建设银行股份有限公司北京中关村软件园支行',
    );
    return $result;
}

/**
 * 公司充值账户，账号对照表
 * @return array     结果
 * @author ming.nie
 */
function getBankAccountMapOptions() {
    $result = array(
        '1' => '11001125700052501376',
    );
    return $result;
}

/**
    * 通用分页列表数据集获取方法
    *
    *  可以通过url参数传递where条件,例如:  index.html?name=asdfasdfasdfddds
    *  可以通过url空值排序字段和方式,例如: index.html?_field=id&_order=asc
    *  可以通过url参数r指定每页数据条数,例如: index.html?r=5
    *
    * @param sting|Model  $model   模型名或模型实例
    * @param array        $where   where查询条件(优先级: $where>$_REQUEST>模型设定)
    * @param array|string $order   排序条件,传入null时使用sql默认排序或模型属性(优先级最高);
    *                              请求参数中如果指定了_order和_field则据此排序(优先级第二);
    *                              否则使用$order参数(如果$order参数,且模型也没有设定过order,则取主键降序);
    *
    * @param array        $base    基本的查询条件
    * @param boolean      $field   单表模型用不到该参数,要用在多表join时为field()方法指定参数
    * @author 朱亚杰 <xcoolcc@gmail.com>
    *
    * @return array|false
    * 返回数据集
    */
   function getLists ($model,$where=array(),$order='',$field=true){
       $options    =   array();
       $REQUEST    =   (array)I('request.');
       if(is_string($model)){
           $model  =   M($model);
       }
   
       $OPT        =   new \ReflectionProperty($model,'options');
       $OPT->setAccessible(true);
   
       $pk         =   $model->getPk();
       if($order===null){
           //order置空
       }else if ( isset($REQUEST['_order']) && isset($REQUEST['_field']) && in_array(strtolower($REQUEST['_order']),array('desc','asc')) ) {
           $options['order'] = '`'.$REQUEST['_field'].'` '.$REQUEST['_order'];
       }elseif( $order==='' && empty($options['order']) && !empty($pk) ){
           $options['order'] = $pk.' desc';
       }elseif($order){
           $options['order'] = $order;
       }
       unset($REQUEST['_order'],$REQUEST['_field']);
   
       if(empty($where)){
           $where  =   array('status'=>array('egt',0));
       }
       if( !empty($where)){
           $options['where']   =   $where;
       }
       $options      =   array_merge( (array)$OPT->getValue($model), $options );
       $total        =   $model->where($options['where'])->count();
   
       if( isset($REQUEST['r']) ){
           $listRows = (int)$REQUEST['r'];
       }else{
           $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
       }
       //超出分页范围后显示最后一页数据
       if(ceil($total/$listRows) < floatval($REQUEST['p'])){
           $_GET['p'] = ceil($total/$listRows);
       }
       $page = new \Think\Page($total, $listRows, $REQUEST);
       $page->setConfig('prev','上一页');
       $page->setConfig('next','下一页');
       $page->setConfig('first','首页');
       $page->setConfig('last','末页');
       $page->lastSuffix = false;
//     	$page->setConfig('theme','%HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%');
       if($total>$listRows){
           $page->setConfig('theme','%HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%');
//     	    $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
       }
       $p =$page->show();
//        $this->assign('_page', $p? $p: '');
//        $this->assign('_total',$total);
       $options['limit'] = $page->firstRow.','.$page->listRows;
   
       $model->setProperty('options',$options);
   
       $data = array();
       $data['data'] = $model->field($field)->select();
       $data['_page'] = $p? $p: '';
       $data['_total'] = $total;
       
       return $data;
   }
   
/**
 * 扣费周期
 * @return array 
 * @author ming.nie
 */
function getDeductPeriodOptions() {
    $result = array(
                    '' => '',
                    '1' => '1个月',
                    '2' => '2个月',
                    '3' => '3个月',
                    '4' => '4个月',
                    '5' => '5个月',
                    '6' => '6个月',
                    '7' => '7个月',
                    '8' => '8个月',
                    '9' => '9个月',
                    '10' => '10个月',
                    '11' => '11个月',
                    '12' => '12个月',
                );
    return $result;
}

/**
 * 充值方式
 * @return array 
 * @author ming.nie
 */
function getRechargeTypeOptions() {
    $result = array(
                    '1' => '银行卡',
                    '2' => '现金',
                );
    return $result;
}


/**
 * 根据ID获取支付方式
 * @param $key
 * @return mixed
 * author CtrL
 */
function getPayMethod($key=null){
    $array = array(
            '1' => '现金',
            '2' => '银行卡',
            '3' => '团购',
            '4' => '会员卡',//Geng.Lin 2015-08-12
            '5' => '券',
            '6' => '支付宝',
            '7' => '微信',//注意 支付方式和web平台的支付代码一致，不能随便更改
            '9' => '招待',
    );

    return $key ? $array[$key] : $array;
}

/**
 * 添加用户日志
 * @return array 
 * @author ming.nie
 */
function addUserLog($params)
{
    $user_info = session('user_info');
    if('root' != $user_info['user_name']) {
        $logLogic = new \Common\Logic\LogLogic();
        $log_params = array();
        $log_params['create_user_id'] = $user_info['user_id'];
        $logLogic->add($log_params);
    }
}

/**
 * 日志行为
 * @return array 
 * @author ming.nie
 */
function getLogOptions() {
    $result = array(
        //系统日志
        U('/Admin/Login/index') => '登录后台',
        U('/Admin/User/add') => '添加用户',
        U('/Admin/User/edit') => '编辑用户',
        U('/Admin/User/update') => '禁用用户',
        U('/Admin/User/addGroup') => '添加角色',
        U('/Admin/User/editGroup') => '编辑角色',
        U('/Admin/User/deleteGroup') => '删除角色',
        U('/Admin/Setting/otherSetting') => '系统设置',
        U('/Admin/User/baseinfo') => '修改资料',
        U('/Admin/User/password') => '修改密码',
        
        //业务日志
        U('/Admin/Cinema/add') => '添加影院',
        U('/Admin/Cinema/edit') => '编辑影院',
        U('/Admin/Cinema/update') => '停用影院',
        U('/Admin/Cinema/initPassword') => '影院密码初始化',
        //U('/Admin/Cinema/recharge') => '影院充值',
        U('/Admin/Cinema/rechargeConfirm') => '到款登记',
        U('/Admin/Cinema/agent1') => '添加代理商',
        U('/Admin/Cinema/agent2') => '编辑代理商',
        U('/Admin/Cinema/agent3') => '停用代理商',
    );
    return $result;
}

/**
 * 获取指定尺寸缩略图
 * @param $picurl
 * @param $size 固定大小：100x100; 比例裁图：100:100
 * author CtrL
 */
function getThumb($picpath, $size){
    if(empty($size) || !file_exists(ROOT_PATH.$picpath) || empty($picpath)) return $picpath;//文件不存在、尺寸部指定，都不裁

    $rs = pathinfo($picpath);

    //分析固定尺寸参数
    if(strpos($size, 'x')){
        list($width, $height) = explode('x', $size);
        $filename = "thumb_{$width}x{$height}_";
    }
    //分析比例尺寸参数
    if(strpos($size, ':')){
        list($w, $h) = explode(':', $size);

        ###########################公约数约去$w $h最简比例###############
        $n = min($w, $h);
        for($i=$n; $i>1; $i--){
            if (is_int($w/$i) && is_int($h/$i) ){
                $w = $w/$i;
                $h = $h/$i;
            }
        }
        ###########################公约数约去$w $h最简比例###############

        $image = new \Think\Image();
        $image->open(ROOT_PATH.$picpath);

        $imageWidth = $image->width();//原宽
        $imageHeight = $image->height();//原高

        if($imageWidth >= $imageHeight){
            $height = $imageHeight;
            $width = $imageHeight * $w / $h;
        } else {
            $height = $imageWidth * $h / $w;
            $width = $imageWidth;
        }
        $filename = "thumb_{$w}_{$h}_";
    }

    //构造新的PIC路径
    $filename .= $rs['basename'];
    $newpath = str_replace($rs['basename'], $filename, $picpath);

    //判断是否存在，存在即返回新的路径直接调用
    if( file_exists( ROOT_PATH.$newpath) ) return $newpath;

    if(strpos($size, ':') === false){
        $image = new \Think\Image();
        $image->open(ROOT_PATH.$picpath);
    }

    // 生成一个居中裁剪为150*150的缩略图并保存为thumb.jpg
    $image->thumb($width, $height,\Think\Image::IMAGE_THUMB_CENTER)->save(ROOT_PATH.$newpath);

    return $newpath;

}   


//根据影院用户ID获取消费主机
function getCinemaHostName($id){
	$map['id'] = $id;
	$info = M('cinema_host')->where($map)->find();
	return $info['host_name'];
}

//根据影院主机获取影院名称
function getCinemaHostNameByHost($host_name){
	$map['host_name'] = $host_name;
	$info = M('cinema_host')->where($map)->find();
	return $info['cinema_name'];
}

//根据主机名称获取主机cinema_host_id
function getCinemaHostId($name){
	$map['host_name'] = $name;
	$info = M('cinema_host')->where($map)->find();
	return $info['id'];
}

//根据主机ID查询影院名称
function getCinemaName($id){
	$map['id'] = $id;
	$info = M('cinema_host')->where($map)->find();
	return $info['cinema_name'];
}	

/**
 * 根据主机名查询影院名称
 */
function getCinemaNameByhost($host_name=''){
    if(empty($host_name)) return '';

    $map['host_name'] = $host_name;
    return M('cinema_host')->where($map)->getField('cinema_name');
}



//根据用户ID查询用户昵称
function getUserName($id){
	$map['user_id'] = $id;
	$info = M('user')->where($map)->find();
	return $info['user_name'];
}	

//通过代理商ID获取用户数量
function getAgentUserNum($id){
	$map['agent_id'] = $id;
	$count = M('cinema_host')->where($map)->count();
	return $count;
}	

//根据ID获取地区名称
function getAreaName($id){
	$map['area_id'] = $id;
	$info = M('area')->where($map)->find();
	return $info['name'];
}

//获取网页内容
function getNetContents($url,$params=array())
{
	!strstr($url,"http://") && $url = "http://".$url;
	$ch = curl_init();
	
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    
	if(isset($params['referer']))
	{
		curl_setopt($ch,CURLOPT_REFERER,$params['referer']);
	}
	if(isset($params['method']) && 'post' == $params['method'])
	{
		curl_setopt($ch, CURLOPT_POST, 1);
		$post_data = '';
		foreach($params['post_data'] as $key => $value)
		{
			$post_data .= $key."=".$value."&";
		}
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
	}
	$contents = curl_exec($ch);
	curl_close($ch);
	return $contents;
}

/**
 * [syncLocalContents 同步数据 云端 -> 本地]
 * @param  string  $url      [目标地址]
 * @param  array   $params   [传递指令]
 * @param  integer $timeout  [超时时间，间隔0.1秒请求一次]
 * @param  boolean $trycron  [是否需要Cron确保数据到达]
 * @param  integer $trytimes [Cron重试次数]
 * @return [type]            [返回内容 OR false]
 */
function syncLocalContents($url,$params=array(),$timeout=10,$trycron=false,$trytimes=3)
{
    //curl
    $contents = syncLocalCurl($url,$params,$timeout);
    //log
    if (false === $contents && true == $trycron)
    {
        $mark = "<|>";
        $syncinfo = $url.$mark.json_encode($params);
        $redis = getRedis();
        $syncinfo_md5 = md5($syncinfo);
        //info count
        $redis->lpush('syncLocal',$syncinfo);
        $redis->set($syncinfo_md5,--$trytimes);
    }
    return $contents;
}

/**
 * [asyncLocalContents 异步数据 本地 -> 云端]
 * @param  string  $url      [目标地址]
 * @param  array   $params   [传递指令]
 * @param  integer $timeout  [超时时间，间隔0.1秒请求一次]
 * @param  boolean $trycron  [是否需要Cron确保数据到达]
 * @param  integer $trytimes [Cron重试次数]
 * @return boolean           [true OR false]
 */
function asyncLocalContents($url,$params=array(),$timeout=10,$trycron=false,$trytimes=3)
{
    $mark = "<|>";
    $asyncinfo = $url.$mark.json_encode($params).$mark.$timeout.$mark.$trycron.$mark.$trytimes;
    $redis = getRedis();
    $re = $redis->lpush('syncLocalList',$asyncinfo);
    return $re;
}

//同步数据 云端 -> 本地 Cron
function syncLocalContentsCron($url,$params=array(),$timeout=10)
{
    //curl
    $contents = syncLocalCurl($url,$params,$timeout);
    $mark = "<|>";
    $syncinfo = $url.$mark.json_encode($params);
    $redis = getRedis();
    $syncinfo_md5 = md5($syncinfo);
    //log
    if (false === $contents)
    {
        //try_times --
        $ltrytimes = $redis->decr($syncinfo_md5);
    }
    //close list
    if($contents || 0 >= $ltrytimes)
    {
        //rm count && list
        $redis->rm($syncinfo_md5);
        $redis->lrem('syncLocal',$syncinfo,0);
    }
    return $contents;
}

//同步数据 云端 -> 本地 curl
function syncLocalCurl($url,$params=array(),$timeout=10)
{
    !strstr($url,"http://") && $url = "http://".$url;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    
    if(isset($params['referer']))
    {
        curl_setopt($ch,CURLOPT_REFERER,$params['referer']);
    }
    if(isset($params['method']) && 'post' == $params['method'])
    {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params['post_data']);
    }
    
    //0.1秒
    $usleep_time = 100000;
    $loop_times = $timeout * 1000000 / $usleep_time;
    for($i=0; $i<$loop_times; $i++)
    {
        usleep($usleep_time);
        $contents = curl_exec($ch);
        if( false !== $contents)
        {
            break;
        }
    }
    curl_close($ch);
    return $contents;
}

/**
 * 调用影院数据接口
 * @param  array:
 *          $params['class'] 类名
 *          $params['method'] 方法名
 * @return array
 * @author ming.nie
 */
function callCinemaInterfaceData($params)
{
    $host_ip = $params['host_ip'];
    return callRemoteInterfaceData($host_ip, $params);
}

/**
 * 调用影院数据接口
 * @param  array:
 *          $params['class'] 类名
 *          $params['method'] 方法名
 * @return array
 * @author ming.nie
 */
function callWebInterfaceData($params)
{
    return callRemoteInterfaceData(C('HOST_WEB'), $params);
}

/**
 * 调用远程接口
 * @param  $host 域名或者ip
 * @param  array:
 *          $params['class'] 类名
 *          $params['method'] 方法名
 * @param  $path 请求路径，默认为/Home/Interface
 * @return array
 * @author ming.nie
 */
function callRemoteInterfaceData($host, $params, $path='/Home/Interface')
{
    $result = array();
    $result['data'] = array();
    $result['data']['status_code'] = 0;
    
    //@by wandaijin
    $url = preg_match("/^(http|https)/", $host) ? $host . $path : 'http://' . $host . $path;
    
    $post_data = array();
    $post_data['class'] = $params['class'];
    $post_data['method'] = $params['method'];
    unset($params['class']);
    unset($params['method']);
    
    $post_data['params'] = json_encode($params);
    $params['post_data'] = $post_data;
    $params['method'] = 'post';
    $res = getNetContents($url, $params);
    $res = json_decode($res, true);

    if(is_array($res)) {
        $result = $res;
    }
    
    return $result;
}


/**
 * 获取远程图片
 * @param  array:
 *          $params['img_url'] 图片地址
 *          $params['save_path'] 存储路径
 * @return array
 * @author ming.nie
 */
function getRemoteImg($img_url, $save_path)
{
    if(!file_exists($save_path))
    {
        mkdirs($save_path, 0777);
    }
    $file_name = getFileNameFromUrl($img_url);
    $data = file_get_contents($img_url);
    file_put_contents($save_path.$file_name, $data);
}

/**
 * 建立多级目录
 * @author ming.nie
 */
function mkdirs($dir)
{
    if(!is_dir($dir))
    {
        if(!mkdirs(dirname($dir)))
        {
            return false;
        }
        if(!mkdir($dir,0777))
        {
            return false;
        }
    }
    return true;
}

//根据url 获取文件名
function getFileNameFromUrl($url)
{
    $result = substr($url,strrpos($url,"/")+1);
    return $result;
}

/**
 * 自定义数字格式化
 * @param float $number
 * @param int $decimals 保留位数
 * @return string
 */
function numFormat( $number, $decimals=0 ) {
    return number_format($number, $decimals, '.', '');
}
/**
 *打印并退出
 * @zhangshiping
 */
function dump_exit($var){
    header('Content-Type: text/html; charset=utf-8');
    $args = func_get_args();
    if(count($args)==1) $args = $args[0];
    dump($args, $echo=true, $label=null, $strict=true);exit;
}

/**
 * 影院类型
 * @return array 
 * @author ming.nie
 */
function getCinemaTypeOptions() {
    //$result = array(
    //                '1' => '普通影院',
    //                '2' => '普通机构',
    //                '3' => 'K米',
    //                '4' => '小帅',
    //                '5' => '欢乐影盟',
    //                '6' => '网吧',
    //                '7' => '道奇',
    //                '8' => '携旅',
    //                '9' => '耀莱',
    //                '10' => '迈智威',
    //                '11' => '1905',
    //            );
    //版权商选项
    $configModel = M('Config');
    $cinema_type_options = $configModel->where('k="cinema_type_options"')->find();
    $cinema_type_options = json_decode($cinema_type_options['v'], true);
    return $cinema_type_options;
}

/**
 * 扣费先后选项
 * @return array 
 * @author ming.nie
 */
function getPayPositionOptions() {
    $result = array(
                    '1' => '先扣费，再使用',
                    '2' => '先使用，再扣费',
                );
    return $result;
}

/**
 * 银行选项
 * @return array 
 * @author ming.nie
 */
function getBankOptions($is_empty=0) {
    if($is_empty) {
        $result[0] = '--';
    }
    $result[1] = '建设银行';
    return $result;
}

/**
 * 银行卡类型选项
 * @return array 
 * @author ming.nie
 */
function getBankCardTypeOptions($is_empty=0) {
    if($is_empty) {
        $result[0] = '--';
    }
    $result[1] = '公司';
    $result[2] = '个人';
    return $result;
}

/**
 * 片库类型
 * @return array 
 * @author ming.nie
 */
function getVideoDataTypeOptions() {
    $result = array(
                    '0' => '请选择',
                    '1' => '20MB 5.1 声道',
                    '2' => '5MB 双声道',
                    '3' => '2MB 双声道',
                );
    return $result;
}

/**
 * 片库网络
 * @return array 
 * @author ming.nie
 */
function getVideoNetOptions() {
    $result = array(
                    '1' => '电信',
                    '2' => '联通',
                    '3' => '大屏专用',
                );
    return $result;
}

/**
 * 片源地址
 * @return array 
 * @author ming.nie
 *20080端口是bt用的，现在还没使用bt
 */
function getVideoDataTypeHostNewOptions() {
    $result = array(
                    '1_1' => 'http://192.168.3.116',
                    '1_2' => 'http://192.168.3.116',
                    '1_3' => 'http://192.168.3.116:20080',
                    '2_1' => 'http://192.168.3.116',
                    '2_2' => 'http://192.168.3.116',
                    '2_3' => 'http://192.168.3.116:20080',
                    '3_1' => 'http://192.168.3.116',
                    '3_2' => 'http://192.168.3.116',
                    '3_3' => 'http://192.168.3.116:20080',
                );
    return $result;
}

//获取影院系统平台：1：1905数娱平台，2：中创数娱
function getSystemPlatformOptions()
{
    $result = array(
                    '1' => '1905数娱平台',
                    '2' => '1905',
                );
    return $result;
}

/**
 * 片库类型主机
 * @return array 
 * @author ming.nie
 */
function getVideoDataTypeHostOptions() {
    $result = array(
                    '0' => '',
                    '1' => 'http://59.56.96.125',
                    '2' => 'http://117.27.142.78',
                );
    return $result;
}

/**
 * 版权系统：地区
 * @return array 
 * @author ming.nie
 */
function getVideoCopyrightAreaOptions() {
    $result = array(
                    '1' => '大陆地区',
                    '2' => '香港地区',
                    '3' => '澳门地区',
                    '4' => '台湾地区',
                );
    return $result;
}

/**
 * 版权系统：行业
 * @return array 
 * @author ming.nie
 */
function getVideoCopyrightIndustryOptions() {
    $result = array(
                    '1' => '微影院',
                    '2' => '酒店',
                    '3' => 'ktv',
                    '4' => '网吧',
                );
    return $result;
}

//html select 控件
function formCheckbox($params)
{
	$name = $params['name'];
	$options = $params['options'];
	$checked = $params['checked'];
	$onclick = $params['onclick'];
	$class = $params['class'];
	$label_class = $params['label_class'];
	!$label_class && $label_class = 'form_checkbox_label';
	if (isset($params['separator']))
		$separator = $params['separator'];
	else
		$separator = "&nbsp;&nbsp;";

	foreach ($options as $key => $val) {
		$current_id = md5($name . $key . microtime());
		$check_str = '';

		if ((is_array($checked) && in_array($key, $checked))) {
			$check_str = 'checked="checked"';
		}
		$parseStr .= '<label class="'.$label_class.'"><input type="checkbox" ' . $check_str . ' onclick="' . $onclick . '" name="' . $name . '[]" value="' . $key . '" class="' . $class . '" id="' . $current_id . '">&nbsp;' . $val . "</label>" . $separator;
	}
	return $parseStr;
}

function trueTab($tab){ /* 转换为数据表的真实名称 */
    return $tab ? C('DB_PREFIX').lower($tab) : false;
}

function lower($str){ /* 将单词转换成有下划线的小写 */
    $res = preg_replace('/([A-Z])/','_$1',$str);
    $res = preg_split('/_/',$res,false,1);
    $res = implode('_',$res);
    return strtolower($res);
}

function getPageSize(){
    return 20;
}

//云视频对称双向加减密类
class TripleDES {
    public static function genIvParameter() {
        return mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_CBC), MCRYPT_RAND);
    }

    private static function pkcs5Pad($text, $blocksize) {
        $pad = $blocksize - (strlen($text) % $blocksize); // in php, strlen returns the bytes of $text
        return $text . str_repeat(chr($pad), $pad);
    }

    private static function pkcs5Unpad($text) {
        $pad = ord($text{strlen($text)-1});
        if ($pad > strlen($text)) return false;
        if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false;
        return substr($text, 0, -1 * $pad);
    }

    public static function encryptText($plain_text, $key, $iv) {
        $padded = TripleDES::pkcs5Pad($plain_text, mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));
        return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $padded, MCRYPT_MODE_CBC, $iv);
    }

    public static function decryptText($cipher_text, $key, $iv) {
        $plain_text = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $cipher_text, MCRYPT_MODE_CBC, $iv);
        return TripleDES::pkcs5Unpad($plain_text);
    }
    public static function decode($cipher_text, $key, $iv) {
        $cipher_text=base64_decode($cipher_text);
        $cipher_text = TripleDES::decryptText($cipher_text, $key, $iv);
        return $cipher_text;
    }
    public static function encode($cipher_text, $key, $iv){
        $cipher_text = TripleDES::encryptText($cipher_text, $key, $iv);
        return base64_encode($cipher_text);
    }
}
function getDateTime(){
    return date('Y-m-d H:i:s');
}
function getData($url,$param=null,$type='get'){
    foreach($param as $key => &$value){
        $value = $key."=".$value;
    }
    if($type=='get' && $param){
        $url = strpos($url, '?') ? $url.'&' : $url.'?';
        $url .= implode('&',$param);
    }
    $ch = curl_init($url) ;
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ;
    if($type=='get'){
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ;
    }else{
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,implode('&',$param));
    }
    $data = json_decode(curl_exec($ch),true);
    curl_close($ch);
    return $data;
}
function VD($flag=0,$result='',$encode=false,$exit=false){
    $dirpath='/data/logs';
    $filename=$dirpath.'/Api.txt';
    date_default_timezone_set('PRC');
    $time=date('Y-m-d H:i:s');
    $str=PHP_EOL.'--------------------'.$time.'---------------------'.PHP_EOL.PHP_EOL;
    $str.='#请求时间：'.$time.PHP_EOL;
    $str.='#请求接口：'.MODULE_NAME.'/'.CONTROLLER_NAME.'/'.ACTION_NAME.PHP_EOL;
    $str.='#请求参数：'.PHP_EOL;
    $t=false;
    foreach($_REQUEST as $key=>$val){
        $val=!empty($val)?$val:'';
        $str.=$key.'=>'.$val.PHP_EOL;
        if(!$t){
            $t=true;
        }
    }
    if(!$t){
        $str.='无请求参数'.PHP_EOL;
    }
    $str.='#返回数据：'.PHP_EOL;
    $str.='标志：'.$flag.PHP_EOL;
    if($result){
        if($encode){
            $str.=json_encode($result);
        }else{
            $str.=$result;
        }

    }else{
        $str.='无数据返回';
    }
    $str.=PHP_EOL.PHP_EOL.'-------------------'.$time.'---------------------'.PHP_EOL;
    file_put_contents($filename,$str.PHP_EOL,FILE_APPEND);
    if($exit){
        exit;
    }
}